<script>
	import {
		mapMutations,
		mapState,
		mapActions
	} from 'vuex';
	import {
		getDw
	} from "@/common/wechat-util.js"
	import siteInfo from '@/common/siteinfo'
	import utils from '@/common/utils.js';
	// #ifdef APP-PLUS
	import mp3 from '@/static/audio/newsUrl.mp3';
	var jyJPush = uni.requireNativePlugin('JY-JPush');
	// #endif
	export default {
		data() {
			return {
				num: 0
			};
		},
		globalData: {
			siteInfo,
			onImgurl: 'https://s.y-bei.cn/static/miniapp/',
			domainDown_url : 'https://s.y-bei.cn/upgraded/sjd/app.apk'
		},
		onLaunch() {
			//绑定全局方法
			uni.$on('getOrderConfigInfo', this.getOrderConfigInfo);
			uni.$on('getSystem', this.getSystem);
			uni.$on('getConnectjyJPush', this.getConnectjyJPush);
			uni.$on('getbusiinfo', this.getbusiinfo);
			uni.$on('setCalllBackFun', this.setCalllBackFun);
			uni.$on('BLEPrinter', this.BLEPrinter);
			uni.$on('IsLogin', this.IsLogin);
			
			// 是否登陆
			this.IsLogin();
			// 获取商家信息
			// this.getbusiinfo();	
			// #ifndef APP-PLUS 
			uni.$on('openLoactionUpdate', this.openLoactionUpdate);
			//初始化消息通知音频
			this.registBackgroundMusic()
			// #endif
			// #ifndef H5
			// 加载历史连接记录
			this.setBLELinkList(this.BLEHistoryLink)
			// 监听蓝牙设备状况
			uni.openBluetoothAdapter({
				success: (res) => {
					console.log('蓝牙模块初始化成功')
					this.BLEConnectStatusLister()
				},
				fail:()=> {
					console.log('蓝牙模块初始化失败')
				}
			})
			try{
				this.getVersionInfo(plus.runtime.version);
			}catch(e){
				//TODO handle the exception
			}
			//#endif
			console.log('App onLaunch');
			
		},
		onShow() {
			// this.getSystem();
			// #ifndef H5
			this.getNotice();
			// #endif
			console.log('App onShow');
		},
		onHide() {
			console.log('App onHide');
			this.setBLEHistoryLink()
		},
		computed: {
			...mapState(['sjxx','ConfigInfo', 'BLELinkList', 'BLEHistoryLink'])
		},
		methods: {
			...mapMutations(['setAccount','setConfigInfo', 'setSystem', 'setSjxx', 'getVersionInfo', 'setBLELinkList',
				'setBLEHistoryLink'
			]),
			// registBackgroundMusic(){
			// 	const account = uni.getStorageSync('account')
			// 	this.mp3Url = 'https://' + account.domainUrl +(account.isDev == 1 ? '/addons/yb_wm/' : '/') + 'web/static/audio/'
			// 	this.bgAudioMannager = uni.getBackgroundAudioManager();
			// 	this.bgAudioMannager.title = '订单通知';
			// 	this.bgAudioMannager.src = this.mp3Url + 'void.mp3';
			// 	this.bgAudioMannager.onEnded(()=>{
			// 		this.bgAudioMannager.src = this.mp3Url + 'void.mp3';
			// 	})
				
			// 	console.log(this.mp3Url + 'void.mp3')
			// },
			BLEConnectStatusLister() {
				uni.onBLEConnectionStateChange((res) => {
					// 该方法回调中可以用于处理连接意外断开等异常情况
					console.log(`蓝牙连接状态:`, res)
					if (!res.connected) {
						let list = this.BLELinkList
						let index = this.BLELinkList.findIndex(item => {
							return item.split('-%-')[0] === res.deviceId
						})
						list.splice(index, 1)
						this.setBLELinkList(list)
					}
				})
				let that = this

				function getPrinterList() {
					let list = []
					// 蓝牙尝试连接历史记录 全部连接尝试后继续下一步
					Promise.all(
						that.BLELinkList.map((item, index) => {
							let deviceId = item.split('-%-')[0]
							let name = item.split('-%-')[1]
							return new Promise((resolve, reject) => {
								uni.createBLEConnection({
									deviceId: deviceId,
									success() {
										list.push(item)
									},
									complete() {
										resolve()
									}
								})
							})

						})
					).then(i => {
						that.setBLELinkList(list)
					})


				}
				getPrinterList()
			},
			getbusiinfo() {
				console.log('开始获取商家信息：')
				this.util
					.request({
						url: this.api.ymmdxx
					})
					.then(res => {
						console.log('商家信息获取成功：',res)
						if (res.code == 1) {
							this.setSjxx(res.data);
						} else {
							this.util.message(res.msg, 3);
						}
					});
			},
			// 是否登录
			IsLogin() {
				// #ifdef MP-WEIXIN
				this.setAccount({
					isDev: this.globalData.siteInfo.isDev,
					domainUrl: this.globalData.siteInfo.siteroot.replace('https://','')
				});
				// #endif
				uni.getStorage({
					key: 'account',
					complete: res => {
						console.log(res)
						if (res.data) {
							if (!res.data.userId) {
								var loginUrl = '/yb_shd/my/login'
								uni.reLaunch({
									url: loginUrl
								});
							} else {
								// #ifdef APP-PLUS
								// 激光绑定回调函数
								this.setCalllBackFun();
								//#endif
								// #ifndef APP-PLUS
								this.openLoactionUpdate()
								// #endif
							}
							// 获取订单设置
							if (res.data.domainUrl) {
								this.getOrderConfigInfo();
								this.getSystem();
								this.getbusiinfo()
							}
						} else {
							var loginUrl = '/yb_shd/my/login'
							uni.reLaunch({
								url: loginUrl
							});
						}
						// #ifndef H5 || MP-WEIXIN
						setTimeout(() => {
							plus.navigator.closeSplashscreen();
						}, 2500);
						//#endif
					}
				});
			},
			// 获取通知权限
			getNotice() {
				// #ifdef APP-PLUS
				var main = plus.android.runtimeMainActivity();
				var pkName = main.getPackageName();
				var NotificationManagerCompat = plus.android.importClass(
					'android.support.v4.app.NotificationManagerCompat');
				var packageNames = NotificationManagerCompat.from(main);
				if (packageNames.areNotificationsEnabled()) {
					console.log('已开启通知权限');
				} else {
					uni.showModal({
						title: '提示',
						content: '请先打开APP通知权限',
						showCancel: false,
						success: function(res) {
							if (res.confirm) {
								var Intent = plus.android.importClass('android.content.Intent');
								var intent = new Intent(
									'android.settings.APP_NOTIFICATION_SETTINGS'); //可设置表中所有Action字段
								intent.putExtra('android.provider.extra.APP_PACKAGE', pkName);
								main.startActivity(intent);
							}
						}
					});
				}
				// #endif
			},
			// 获取订单设置
		  async getOrderConfigInfo() {
				  await	this.util
						.request({
							url: this.api.strogConfig,
							data: {
								ident: 'takeawayVoice'
							}
						})
						.then(res => {
							if (res.code == 1) {
								this.setConfigInfo(res.data);
							}
						});
			
			},
			// 获取配置信息
			getSystem() {
				this.util
					.request({
						url: this.api.config,
						data: {
							ident: 'system'
						}
					})
					.then(res => {
						console.log('公共信息:', this.res)
						if (res.code == 1) {
							res.data.color = res.data.color || '#FE9367';
							res.data.custom = {
								hbfh: '￥',
								hbmc: '元'
							};
							this.setSystem(res.data);
						}
					});
			},
		async	fetchDataAndPalyMusic(data){
					uni.$emit('refreshOrderList')
					// #ifdef APP-PLUS
					// this.getSystem();
					await	this.getOrderConfigInfo()
					console.log(this.ConfigInfo.newOrder)
					const autop = uni.createInnerAudioContext();
					autop.src = mp3
					autop.onCanplay(a => {
						autop.loop = true;
						autop.play();
						if (this.ConfigInfo.newOrder != 0) {
							let leng = autop.duration * 1000 * this.ConfigInfo.newOrder;
							if (this.ConfigInfo.newOrder != 3) {
								setTimeout(() => {
									autop.loop = false;
									autop.stop();
								}, leng);
							}
						}
					});
					// #endif
					
					// #ifndef APP-PLUS
					if(data.voiceType === 'newOrder'){
						this.bgAudioMannager.src = data.receiveStatus === '2' ? this.mp3Url + 'newsUrl.mp3' : this.mp3Url + 'autoOrderUrl.mp3'
					}else{
						this.bgAudioMannager.src = this.mp3Url + 'cancelOrderUrl.mp3';
					}
					this.bgAudioMannager.play()
					console.log(this.mp3Url + 'newsUrl.mp3')
					setTimeout(()=>{
						this.bgAudioMannager.src = this.mp3Url + 'void.mp3';
						this.bgAudioMannager.pause()
					},6000)
					// #endif
					
			},
			// 判断后台定位功能是否打开 用来避免小程序切后台被杀进程
			// #ifdef MP-WEIXIN
			openLoactionUpdate(){
				let that = this
				// that.getNewOrderInfo()
				function getOrder(res){
					wx.onLocationChange(data=>{
						that.getNewOrderInfo()
					})
				}
				uni.getSetting({
					success:res=>{
						console.log(res)
						if(!res.authSetting['scope.userLocationBackground']){
							this.util.modal('位置信息授权时需要选择,使用小程序期间和离开小程序后选项','开启位置共享').then(res=>{
								uni.openSetting({
									complete:res=>{
										if(res.authSetting['scope.userLocationBackground']){
											wx.startLocationUpdateBackground({success:getOrder})
										}
									}
								})
							})
						}else{
							console.log('更新位置信息')
							wx.startLocationUpdateBackground({success:getOrder})
						}
					}
				})
			},
			// #endif
			// 绑定回调方法
			setCalllBackFun() {
				// 连接激光推送
				this.generateRandomNum();
				// 获取 registrationID， 返回的数据会有registrationID，errorCode
				jyJPush.getRegistrationID(result => {
					if (result.errorCode == 0) {
						this.util
							.request({
								url: this.api.registrationId,
								method: 'POST',
								data: {
									registrationId: result.registrationID
								}
							})
							.then(res => {
								console.log('成功：',res);
								console.log('成功传入registrationId：' + result.registrationID);
								this.setAccount({
									registrationID: result.registrationID
								});
							});
					}
				});
				//监听成功后，若收到推送，会在result返回对应的数据；数据格式保持极光返回的安卓/iOS数据一致
				jyJPush.addJYJPushReceiveNotificationListener(result => {
					console.log('极光：', result)
					console.log(result.notificationContent + '!');
					// 自动打印订单
					this.getNewOrderInfo()
				});
				//监听成功后，若点击推送消息，会触发result；数据格式保持极光返回的安卓/iOS数据一致
				jyJPush.addJYJPushReceiveOpenNotificationListener(result => {
					console.log(result);
					console.log('用户点击了新订单！：' + result);
					uni.reLaunch({
						url: '/yb_shd/index/index'
					});
				});
			},
			// 生成随机签名
			generateRandomNum() {
				uni.getStorage({
					key: 'jyJPushUuid',
					success: res => {
						// 调用极光推送
						// #ifndef H5
						this.getConnectjyJPush();
						// #endif
					},
					fail: err => {
						const s = [];
						const hexDigits = '0123456789abcdef';
						for (let i = 0; i < 36; i++) {
							s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
						}
						s[14] = '4'; // bits 12-15 of the time_hi_and_version field to 0010
						s[19] = hexDigits.substr((s[19] & 0x3) | 0x8,
							1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
						const uuid = s.join('');
						uni.setStorage({
							key: 'jyJPushUuid',
							data: uuid,
							complete: () => {
								// #ifndef H5
								this.getConnectjyJPush();
								// #endif
							}
						});
					}
				});
			},
			// 连接极光推送
			getConnectjyJPush() {
				const uuid = uni.getStorageSync('jyJPushUuid');
				jyJPush.setJYJPushAlias({
						userAlias: uuid.replace(/\-/g, '')
					},
					result => {
						// console.log("成功连接激光推送=", result)
						jyJPush.getJYJPushAlias({}, result => {
						})
						//  设置成功或者失败，都会通过这个result回调返回数据；数据格式保持极光返回的安卓/iOS数据一致
						//  注：若没有返回任何数据，考虑是否初始化完成
						if (result.iResCode == 0) {
							console.log("iResCode=" + result.iResCode + '==>成功连接激光推送!')
						} else {
							this.getConnectjyJPush();
						}
					}
				);

			},
			//获取新订单info
			getNewOrderInfo:utils.throttle(async function(e){
				const account = uni.getStorageSync('account')
				var that = this
				let {data} = await that.util
							.request({
								url: that.api.newOrderInfo,
								method: 'get',
								data:{
									openId:account.openid
								}
							})
				console.log('订单info:',data)
				
				if(data){
					if(data.voiceType){ //自动接单直接打印
						that.BLEPrinter(that.BLELinkList,data)
						console.log('请求数据和播放音乐')
						that.fetchDataAndPalyMusic(data)
					}
				}
			},5000),
			// 蓝牙打印
			BLEPrinter(BLELinkList, orderInfo) {
				orderInfo.storeName = this.sjxx.name
				// todo 判断订单需要打印 商家联 后厨联 顾客联 配送联 现在只需要考虑本地蓝牙打印机配置
				console.log('打印机:', BLELinkList)
				BLELinkList.map(pirinter => {
					// switch 语句 根据orderInfo里面的type判断 打印类别 todo
					console.log('选择打印机:', pirinter)
					this.bleSend.receiptTest(pirinter, orderInfo)
				})
			}
		}
	};
</script>

<style lang="scss">
	/*每个页面公共css */
	// #ifndef APP-NVUE
	@import 'uview-ui/index.scss';
	@import './common/styles/index.css';
	// #endif
</style>
